import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Alert,
    FlatList,
    TextInput,
    Linking,
    Image,
    DeviceEventEmitter,
    ScrollView
} from 'react-native';

import moment from 'moment';
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import AndroidModule from "../../utils/AndroidConnent";
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction'
import Header from "../../components/header";
import Picker from 'react-native-picker'
import ImageCropPicker from 'react-native-image-crop-picker';
import Upload from '../../components/upload/Upload'
import CommonConfirmPop from '../../components/dialog/CommonConfirmPop';
import BigImageContainer from '../../components/Tool/BigImageContainer';

const screenW = Dimensions.get('window').width;

let initialPage
let navigation
/**
 * 确认收货-上传过户资料
 */
export default class ConfirmReceiveCar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            payEvidence: '',
            payType: '',

            from: this.props.route.params.from,//1 提交 2查看 3订单已完成上传资料
            orderNo: this.props.route.params.orderNo,
            transferInvoice: '',
            driveLicenseFront: '',
            driveLicenseBack: '',
            idCardFront: '',
            idCardBack: '',
            carRegBookList: [],
            uploadType: '',
            dialogVisible: false,

            showPicList: [],
            showPics: false
        }
    }

    componentDidMount() {
        console.log('this.state.from', this.state.from)
        if (this.state.orderNo != null && this.state.orderNo != '' && this.state.from == 2) {
            this.getOrderDetail()
        }
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} hideSepLine={true} Title={this.state.from == 2 ? '过户资料' : '资料上传'} ></Header>

                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false} >
                    {this.state.from == 2 ? null :
                        <View style={{ marginLeft: 16, marginTop: 10 }}>
                            <Text style={{ fontSize: 16, color: '#ED542E' }}>请上传过户资料</Text>
                        </View>
                    }


                    <View style={styles.uploadContain}>
                        <Text style={styles.uploadTipTitleText}>新车行驶证照片<Text style={{ color: '#ED542E' }}>*</Text></Text>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>

                            {this.state.driveLicenseFront != '' ?
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    if (this.state.from == 2) {
                                        this.setState({
                                            showPicList: [{ url: getImgUrl(this.state.driveLicenseFront) }],
                                            showPics: true
                                        })

                                    }
                                }} style={{ width: 85 }}>
                                    <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.driveLicenseFront) }} />

                                    {this.state.from == 2 ? null :
                                        <TouchableOpacity
                                            onPress={() => {
                                                this.setState({
                                                    driveLicenseFront: ''
                                                })
                                            }}
                                            style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                            <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                        </TouchableOpacity>
                                    }

                                </TouchableOpacity>

                                :
                                this.state.from == 2 ? null :
                                    <View style={{ flexDirection: 'column' }}>
                                        <TouchableOpacity
                                            onPress={() => {
                                                this.uploadPayImg(1)
                                            }}>
                                            <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                        </TouchableOpacity>
                                        <Text style={{ fontSize: 12, color: '#999999', width: 75, textAlign: 'center', marginTop: 5 }}>行驶证正页</Text>
                                    </View>

                            }

                            {this.state.driveLicenseBack != '' ?
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    if (this.state.from == 2) {
                                        this.setState({
                                            showPicList: [{ url: getImgUrl(this.state.driveLicenseBack) }],
                                            showPics: true
                                        })

                                    }
                                }} style={{ width: 85 }}>
                                    <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.driveLicenseBack) }} />

                                    {this.state.from == 2 ? null :
                                        <TouchableOpacity
                                            onPress={() => {
                                                this.setState({
                                                    driveLicenseBack: ''
                                                })
                                            }}
                                            style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                            <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                        </TouchableOpacity>
                                    }

                                </TouchableOpacity>

                                :
                                <View style={{ flexDirection: 'column' }}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            this.uploadPayImg(2)
                                        }}>
                                        <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                    </TouchableOpacity>
                                    <Text style={{ fontSize: 12, color: '#999999', width: 75, textAlign: 'center', marginTop: 5 }}>行驶证副页</Text>
                                </View>

                            }
                        </View>

                    </View>

                    <View style={styles.uploadContain}>
                        <Text style={styles.uploadTipTitleText}>登记证照片<Text style={{ color: '#ED542E' }}>*</Text></Text>


                        <View style={{ flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap' }}>
                            {this.state.carRegBookList.map((item, index) => {
                                return (
                                    <TouchableOpacity style={{ width: 85 }} activeOpacity={0.8} onPress={() => { this.setState({ showPicList: [{ url: getImgUrl(item) }], showPics: true }) }}>
                                        <Image style={styles.uploadImg} source={{ uri: getImgUrl(item) }} />

                                        {this.state.from == 2 ? null :
                                            <TouchableOpacity
                                                onPress={() => {
                                                    let temp = []
                                                    for (let i = 0; i < this.state.carRegBookList.length; i++) {
                                                        if (i != index) {
                                                            temp.push(this.state.carRegBookList[i])
                                                        }
                                                    }
                                                    this.setState({
                                                        carRegBookList: temp
                                                    })
                                                }}
                                                style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>

                                                <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                            </TouchableOpacity>
                                        }


                                    </TouchableOpacity>
                                )
                            })}

                            {this.state.from == '2' ? null :
                                <TouchableOpacity
                                    onPress={() => {
                                        this.uploadPayImg(3)
                                    }}>
                                    <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                </TouchableOpacity>}
                        </View>

                    </View>

                    <View style={styles.uploadContain}>
                        <Text style={styles.uploadTipTitleText}>新车主身份证照片<Text style={{ color: '#ED542E' }}>*</Text></Text>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>

                            {this.state.idCardFront != '' ?
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    if (this.state.from == 2) {
                                        this.setState({
                                            showPicList: [{ url: getImgUrl(this.state.idCardFront) }],
                                            showPics: true
                                        })

                                    }
                                }} style={{ width: 85 }}>
                                    <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.idCardFront) }} />

                                    {this.state.from == 2 ? null :
                                        <TouchableOpacity
                                            onPress={() => {
                                                this.setState({
                                                    idCardFront: ''
                                                })
                                            }}
                                            style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                            <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                        </TouchableOpacity>
                                    }

                                </TouchableOpacity>

                                :
                                <View style={{ flexDirection: 'column' }}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            this.uploadPayImg(4)
                                        }}>
                                        <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                    </TouchableOpacity>
                                    <Text style={{ fontSize: 12, color: '#999999', width: 75, textAlign: 'center', marginTop: 5 }}>身份证人像面</Text>
                                </View>

                            }

                            {this.state.idCardBack != '' ?
                                <TouchableOpacity activeOpacity={0.8} onPress={() => {
                                    if (this.state.from == 2) {
                                        this.setState({
                                            showPicList: [{ url: getImgUrl(this.state.idCardBack) }],
                                            showPics: true
                                        })

                                    }
                                }} style={{ width: 85 }}>
                                    <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.idCardBack) }} />

                                    {this.state.from == 2 ? null :
                                        <TouchableOpacity
                                            onPress={() => {
                                                this.setState({
                                                    idCardBack: ''
                                                })
                                            }}
                                            style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                            <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                        </TouchableOpacity>
                                    }

                                </TouchableOpacity>

                                :
                                <View style={{ flexDirection: 'column' }}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            this.uploadPayImg(5)
                                        }}>
                                        <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                    </TouchableOpacity>
                                    <Text style={{ fontSize: 12, color: '#999999', width: 75, textAlign: 'center', marginTop: 5 }}>身份证国徽面</Text>
                                </View>

                            }
                        </View>

                    </View>

                    <View style={styles.uploadContain}>
                        <Text style={styles.uploadTipTitleText}>过户发票<Text style={{ color: '#ED542E' }}>*</Text></Text>

                        {this.state.transferInvoice != '' ?
                            <TouchableOpacity style={{ width: 85 }} activeOpacity={0.8} onPress={() => { if (this.state.from == 2) { this.setState({ showPicList: [{ url: getImgUrl(this.state.transferInvoice) }], showPics: true }) } }}>
                                <Image style={styles.uploadImg} source={{ uri: getImgUrl(this.state.transferInvoice) }} />

                                {this.state.from == 2 ? null :
                                    <TouchableOpacity
                                        onPress={() => {
                                            this.setState({
                                                transferInvoice: ''
                                            })
                                        }}
                                        style={{ position: 'absolute', right: 0, top: 5, width: 30, height: 30 }}>
                                        <Image style={{ width: 18, height: 18, marginLeft: 12 }} source={require('source/image/delete_car_icon.png')} />
                                    </TouchableOpacity>

                                }

                            </TouchableOpacity>

                            :

                            this.state.from == '2' ? null :
                                <TouchableOpacity
                                    onPress={() => {
                                        this.uploadPayImg(6)
                                    }}>
                                    <Image style={styles.uploadImg} source={require('source/image/add_img_icon.png')} />
                                </TouchableOpacity>

                        }
                    </View>
                </ScrollView>


                {this.state.from == '2' ? null
                    :

                    <View style={styles.bottomContain}>
                        {this.state.from == '1' ?
                            <TouchableOpacity
                                style={styles.bottomSkipButton}
                                onPress={() => {
                                    this.setState({
                                        dialogVisible: true,
                                        isSkip: true
                                    })
                                }}>
                                <Text style={styles.bottomButtonText}>先跳过</Text>
                            </TouchableOpacity>
                            : null
                        }

                        <TouchableOpacity
                            style={styles.bottomButton}
                            onPress={() => {
                                // this.setState({
                                //     dialogVisible: true,
                                //     isSkip: false
                                // })
                                this.updateVehicleTransferInfo()

                            }}>
                            <Text style={styles.bottomButtonText}>提交</Text>
                        </TouchableOpacity>
                    </View>

                }


                {this.state.dialogVisible ?
                    <CommonConfirmPop
                        visible={this.state.dialogVisible}
                        content={'确认收货后'}
                        redText={'尾款将支付给卖家'}
                        content2={'，是否确认收货？'}
                        onClose={() => {
                            this.setState({
                                dialogVisible: false
                            })


                        }}
                        onCancel={() => {
                            this.setState({
                                dialogVisible: false
                            })

                        }}
                        onSure={() => {
                            this.setState({
                                dialogVisible: false
                            })
                            // this.updateVehicleTransferInfo()
                            this.orderConfirmReceipt()

                        }}
                        sureText={'确认'}
                        cancelText={'返回'}

                    >

                    </CommonConfirmPop>
                    :
                    null
                }

                {
                    this.state.showPics ?
                        <BigImageContainer
                            idx={0}
                            images={this.state.showPicList}
                            closeHandler={(index) => {
                                this.setState({

                                    showPics: false
                                })
                            }}
                        />
                        :
                        null
                }


                <Loading onRef={(ref) => (this.Loading = ref)} loadingText={'上传中...'} />



            </View>
        )
    }


    uploadPayImg(uploadType) {
        this.setState({
            uploadType: uploadType
        })

        const option = { mediaType: "photo", cropping: false, multiple: false, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openPicker(option).then(images => {
            console.log('images = ', images)
            if (images.path) {
                if (this.Loading) {
                    this.Loading.show();
                }
                Upload.getAlipz(images.path, Upload.OSS_CONTRACT, this.uploadafterfun);//获取阿里凭证。
            }


        }, (error) => {
            // alert(error);
        });
    }

    uploadafterfun = (bojkey) => {
        if (this.Loading) {
            this.Loading.hide();
        }

        console.log('uploadType', this.state.uploadType)
        if (this.state.uploadType == 1) {
            this.setState({
                driveLicenseFront: bojkey
            })
        } else if (this.state.uploadType == 2) {
            this.setState({
                driveLicenseBack: bojkey
            })
        } else if (this.state.uploadType == 3) {
            let temp = this.state.carRegBookList
            temp.push(bojkey)
            this.setState({
                carRegBookList: temp
            })
        } else if (this.state.uploadType == 4) {
            this.setState({
                idCardFront: bojkey
            })
        } else if (this.state.uploadType == 5) {
            this.setState({
                idCardBack: bojkey
            })
        } else if (this.state.uploadType == 6) {
            this.setState({
                transferInvoice: bojkey
            })
        }

    }

    updateVehicleTransferInfo() {

        if (this.state.driveLicenseFront == '') {
            ToastToUser('请上传行驶证正页')
            return
        }
        if (this.state.driveLicenseBack == '') {
            ToastToUser('请上传行驶证反页')
            return
        }
        if (this.state.idCardFront == '') {
            ToastToUser('请上传身份证人像面')
            return
        }
        if (this.state.idCardBack == '') {
            ToastToUser('请上传身份证国徽面')
            return
        }
        if (this.state.carRegBookList.length == 0) {
            ToastToUser('请上传登记证照片')
            return
        }
        if (this.state.transferInvoice == '') {
            ToastToUser('请上传过户发票')
            return
        }

        let param = {
            orderNo: this.state.orderNo,
            carLicenseFront: this.state.driveLicenseFront,
            carLicenseBack: this.state.driveLicenseBack,
            idFront: this.state.idCardFront,
            idBack: this.state.idCardBack,
            carRegBookList: this.state.carRegBookList,
            otherCertList: [this.state.transferInvoice]
        }

        if (this.Loading) {
            this.Loading.show();
        }


        HttpUtils.postRequest(HttpUrls.updateVehicleTransferInfo, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('过户资料上传成功')
                    // 

                    // navigation.goBack()
                    if(this.state.from == '1'){
                        this.setState({
                            dialogVisible: true,
                            isSkip: false
                        })
                    }else{
                        DeviceEventEmitter.emit('refreshOrderDetail', {})
                        navigation.goBack()
                    }
                    
                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {

            })

    }

    orderConfirmReceipt() {

        let param = {
            orderNo: this.state.orderNo,
        }

        if (this.Loading) {
            this.Loading.show();
        }


        HttpUtils.getRequest(HttpUrls.orderConfirmReceipt, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('确认收货成功')
                    DeviceEventEmitter.emit('refreshOrderDetail', {})

                    navigation.goBack()
                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {

            })

    }

    getOrderDetail() {

        let param = {

            orderNo: this.state.orderNo
        }

        HttpUtils.getRequest(HttpUrls.getDetailsByOrderNo, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0 && result.data) {
                    let certificateInfoRO = result.data.certificateInfoRO
                    console.log('certificateInfoRO', certificateInfoRO)
                    this.setState({
                        driveLicenseFront: certificateInfoRO.carLicenseFront,
                        driveLicenseBack: certificateInfoRO.carLicenseBack,
                        idCardFront: certificateInfoRO.idFront,
                        idCardBack: certificateInfoRO.idBack,
                        carRegBookList: certificateInfoRO.carRegBookList,
                        transferInvoice: certificateInfoRO.otherCertList ? certificateInfoRO.otherCertList[0] : '',
                    })

                }

            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },

    arrowImg: {
        width: 16,
        height: 16
    },

    uploadContain: {
        marginLeft: 16,
        marginRight: 16,
        marginTop: 10,
        marginBottom: 10,
        backgroundColor: '#fff',
        borderRadius: 4,
        padding: 16
    },

    uploadTipTitleText: {
        fontSize: 16,
        color: '#222222',
        fontWeight: '500'
    },

    uploadImg: {
        width: 75,
        height: 75,
        marginTop: 16,

        marginRight: 16,
        borderRadius: 4,

    },

    payTypeContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        backgroundColor: '#fff',
        marginLeft: 16,
        marginRight: 16,
        height: 46,
        borderRadius: 4,
        paddingHorizontal: 16
    },
    typeTitle: {
        fontSize: 14,
        color: '#333333',
        fontWeight: '500'
    },
    typeText: {
        fontSize: 14,
        color: '#999999',

    },

    bottomContain: {

        width: '100%',
        height: 100,
        flexDirection: 'row',

        backgroundColor: '#fff',
    },
    bottomButton: {
        margin: 15,
        height: 46,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#FFE000',
        flex: 1,
        borderRadius: 46
    },
    bottomSkipButton: {
        margin: 15,
        height: 46,
        alignItems: 'center',
        justifyContent: 'center',

        flex: 1,
        borderRadius: 46,
        borderWidth: 1,
        borderColor: '#e4e4e4'
    },
    bottomButtonText: {
        fontSize: 16,
        color: '#333',
        fontWeight: '500'
    },

})